package com.supcon.tinyportal.tags;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.supcon.tinyportal.util.Constants;

public class PortletTag extends BodyTagSupport {

	private static final long serialVersionUID = 1L;

	private String id;
	private String title;
	protected String style = null;
	protected String styleClass = null;
	
	/**
	 * @return the style
	 */
	public String getStyle() {
		return style;
	}

	/**
	 * @param style
	 *            the style to set
	 */
	public void setStyle(String style) {
		this.style = style;
	}

	/**
	 * @return the styleClass
	 */
	public String getStyleClass() {
		return styleClass;
	}

	/**
	 * @param styleClass
	 *            the styleClass to set
	 */
	public void setStyleClass(String styleClass) {
		this.styleClass = styleClass;
	}

	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}

	/**
	 * @param title
	 *            the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}

	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	void prepareAttribute(StringBuffer handlers, String name, Object value) {
		if (value != null) {
			handlers.append(" ");
			handlers.append(name);
			handlers.append("=\"");
			handlers.append(value);
			handlers.append("\"");
		}
	}

	public int doStartTag() throws JspException {
		if (id == null) {
			throw new JspException("Portlet must have an ID specified in Portlet tag");
		}
		pageContext.setAttribute(Constants.PORTLET_ID, id);

		JspWriter out = pageContext.getOut();
		try {
			StringBuffer results = new StringBuffer("<div");
			prepareAttribute(results, "id", getId() + Constants.PORTLET_ID_SUFFIX);
			prepareAttribute(results, "class", getStyleClass());
			prepareAttribute(results, "style", getStyle());
			results.append(">");
			results.append("<h2>");
			results.append(getTitle());
			results.append("</h2>");
			out.write(results.toString());
		} catch (IOException e) {
			throw new JspException(e);
		}

		return EVAL_BODY_INCLUDE;
	}

	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.write("</div>");
		} catch (IOException e) {
			throw new JspException(e);
		}
		return SKIP_PAGE;
	}
}
